package Servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import javabean.Admin;
import javabean.Detail;
import javabean.ResultData;
import javabean.User;
import service.AdminModuleService;
import serviceimpl.AdminModuleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static java.lang.Integer.parseInt;

@WebServlet(name = "AdminMainServlet", value = "/adminMain")
public class AdminMainServlet extends HttpServlet {
    private static final AdminModuleService ADMIN_MODULE_SERVICE = new AdminModuleServiceImpl();
    private static ArrayList<Admin> admins = null;
    private static ArrayList<User> users = null;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        int code = Integer.parseInt(req.getParameter("code"));
        System.out.println(code);
        System.out.println("--------------------");

        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        //System.out.println(admin);

        if (admins == null) {
            admins = ADMIN_MODULE_SERVICE.findAllAdmin();
        }
        if (users == null) {
            users = ADMIN_MODULE_SERVICE.findAllUser();
        }

        ObjectMapper js = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();

        A:
        switch (code) {
            case -1: {
                session.invalidate();
                map.put("res", -1);
                map.put("redirectUrl", "login.html");
                break;
            }
            case 1: {
                map.put("data", admin);
                break;
            }
            case 2: {
                String password = req.getParameter("password");
                String newPassword = req.getParameter("newPassword");
                String reNewPassword = req.getParameter("reNewPassword");
                //System.out.println(password);
                //System.out.println(newPassword);
                //System.out.println(reNewPassword);
                //System.out.println("----------------------");

                Boolean resReset = null;
                String msg = null;
                if (admin.getPassWord().equals(password)) {
                    if (newPassword != null && !newPassword.equals("")) {
                        if (newPassword.equals(reNewPassword)) {
                            resReset = ADMIN_MODULE_SERVICE.adminResetPassword(admin.getId(), newPassword);
                            msg = "修改密码成功";
                            admin = ADMIN_MODULE_SERVICE.findMyAdminByUsername(admin.getUserName());
                            session.setAttribute("admin", admin);
                        } else {
                            resReset = false;
                            msg = "修改失败，两次密码不相同";
                        }
                    } else {
                        resReset = false;
                        msg = "修改失败，新密码为空";
                    }
                } else {
                    resReset = false;
                    msg = "修改失败，旧密码不正确";
                }
                map.put("msg", msg);
                map.put("resReset", resReset);
                break;
            }
            case 21: {
            }
            case 22: {
                String type = req.getParameter("type");
                int pageSize = parseInt(req.getParameter("pageSize"));
                int currentPage = parseInt(req.getParameter("currentPage"));
                //System.out.println("表格方法参数");

                //System.out.println("type:" + type);
                //System.out.println("currentPage:" + currentPage);
                //System.out.println("pageSize:" + pageSize);
                //System.out.println("---------------------------");

                Integer size;
                Boolean userData;
                if ("user".equals(type)) {
                    userData = true;
                    size = users.size();
                } else {
                    userData = false;
                    size = admins.size();
                }

                ArrayList datas = new ArrayList<>();
                if (userData) {
                    for (int i = pageSize * (currentPage - 1); i < users.size() && i < pageSize * currentPage; i++) {
                        datas.add(users.get(i));
                    }
                } else {
                    for (int i = pageSize * (currentPage - 1); i < admins.size() && i < pageSize * currentPage; i++) {
                        datas.add(admins.get(i));
                    }
                }
                ResultData<Detail> resultData = new ResultData<>(size, "", datas);
                map.put("resultData", resultData);
                break;
            }
            case 31: {
                Integer id = Integer.valueOf(req.getParameter("id"));
                System.out.println("重置密码id:" + id);

                Integer idx = null;
                for (User user : users) {
                    if (Objects.equals(user.getId(), id)) {
                        user.setPassWord("123456");
                        break;
                    }
                }
                ADMIN_MODULE_SERVICE.userResetUserPassword(id, "123456");
                break;
            }
            case 32: {
                Integer id = Integer.valueOf(req.getParameter("id"));
                System.out.println("id:" + id);

                Integer idx = null;
                for (int i = 0; i < users.size(); i++) {
                    User user = users.get(i);
                    if (Objects.equals(user.getId(), id)) {
                        idx = i;
                        break;
                    }
                }
                System.out.println(users.get(idx));
                users.remove(idx.intValue());
                System.out.println(users.get(idx));
                ADMIN_MODULE_SERVICE.removeUser(id);
                System.out.println("删除完毕");
                break;
            }
            case 4: {
                Integer id = Integer.valueOf(req.getParameter("id"));
                System.out.println("id:" + id);
                System.out.println("管理员删除");

                int idx = -1;
                for (int i = 0; i < admins.size(); i++) {
                    Admin user = admins.get(i);
                    if (Objects.equals(user.getId(), id)) {
                        idx = i;
                        break;
                    }
                }
                //System.out.println(admins.get(idx));
                if(idx != -1) {
                    admins.remove(idx);
                }
                //System.out.println(admins.get(idx));
                ADMIN_MODULE_SERVICE.removeAdmin(id);
                System.out.println("删除完毕");
                break A;
            }
            case 5: {
                String type = req.getParameter("type");
                String email = req.getParameter("email");
                String username = req.getParameter("username");
                String password = req.getParameter("password");
                String name = req.getParameter("name");
                String newPassword = req.getParameter("newPassword");
                //System.out.println("type:" + type);
                //System.out.println("email:" + email);
                //System.out.println("username:" + username);
                //System.out.println("name:" + name);
                //System.out.println("password:" + password);
                //System.out.println("newPassword:" + newPassword);
                //System.out.println("--------------------------------");

                Boolean flag = null;
                if ("user".equals(type)) {
                    flag = true;
                } else {
                    flag = false;
                }
                if (!password.equals(newPassword)) {
                    map.put("res", -1);
                    map.put("msg", "两次输入密码不一致，请重新输入");
                    break A;
                }
                if (flag) {
                    for (int i = 0; i < users.size(); i++) {
                        if (users.get(i).getUserName().equals(username)) {
                            map.put("res", -1);
                            map.put("msg", "该用户账户已存在，请重新注册！");
                            break A;
                        }
                    }
                    ADMIN_MODULE_SERVICE.createUser(username, password, name, email, 0.0);
                    users.add(new User(username, password, name, email, 0.0));
                    map.put("res", 1);
                    map.put("msg", "用户添加成功");
                    break A;
                } else {
                    for (int i = 0; i < admins.size(); i++) {
                        if (admins.get(i).getUserName().equals(username)) {
                            map.put("res", -1);
                            map.put("msg", "该管理员账户已存在，请重新注册！");
                            break A;
                        }
                    }
                    ADMIN_MODULE_SERVICE.createAdmin(username, password, name, email, "瞎几把创建管理员");
                    admins.add(new Admin(username, password, name, email, "瞎几把创建管理员"));
                    map.put("res", 1);
                    map.put("msg", "管理员添加成功");
                    break A;
                }

            }
            default: {
                map.put("msg", "提交状态码错误");
                break;
            }
        }
        resp.getWriter().println(js.writeValueAsString(map));
    }
}
